package com.example.projects;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

import android.os.AsyncTask;
import android.widget.ImageView;
import android.app.ProgressDialog;
import android.content.*;
import android.graphics.drawable.Drawable;

public class getImage extends AsyncTask<String, Void, Drawable> {
    private Context mContext;
    private ProgressDialog dialog;
    private ImageView view;
    private InputStream is=null;
    
    public getImage(Context c, ImageView v) {
            this.mContext = c;
            this.view = v;
    }
    
    @Override
    protected void onPreExecute() {
        dialog = ProgressDialog.show(this.mContext, "", 
        "Downloading image. Please wait...",             		
        true,
		true,
		new DialogInterface.OnCancelListener() {
			
			@Override
			public void onCancel(DialogInterface dialog) {
				getImage.this.cancel(true);
				onPostExecute(null);
			}
		});
    }
    
    @Override
    protected void onPostExecute(Drawable r) {
        dialog.dismiss();
        if(r != null) {
        	view.setImageDrawable(r);
        }else {
        	view.setImageResource(R.drawable.noimage);
        }
    }
    
    
    @Override
    public Drawable doInBackground(String... args) {
    //public void getData(String contents, String path){

    	Drawable draw = null;
        String imagestr = args[0];
        try {
        	// have some error checking for if image taking too long to download
        	// or if image file is not on server
        	URL url = new URL("http://www.cpt3004.dynalias.org:81/cpt/phpappfixed/admin/image/"+imagestr);
        	URLConnection urlConnection = url.openConnection();
        	urlConnection.setConnectTimeout(3000);
        	urlConnection.setReadTimeout(3000);
        	is = (InputStream) url.getContent();
        	
        	draw = Drawable.createFromStream(is, "src");
        	safeClose();
        } catch (Exception e) {
        	
        	draw = null;
            e.printStackTrace();
        }
        return draw;
    	//ConnectionManager.getInstance().didComplete(this);
    }
    
    private void safeClose() {
    	if(!is.equals(null)) {
    		try {
				is.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
    	}
    }
}